<?php

	namespace app\data\controller\api;

	use app\data\model\DataUser;
	use app\data\model\DataUserToken;
	use app\data\model\ShopOrder;
	use app\data\service\MessageService;
	use app\data\service\UserAdminService;
	use think\admin\Controller;
	use think\admin\model\SystemUser;
	use think\cache\driver\Redis;
	use app\data\controller\api\Sendsms;
	use think\Log;
	use WeMini\Crypt;

	require_once './vendor/TLSSigAPIv2.php';

	/**
	 * 用户登录注册接口
	 * Class Login
	 * @package app\data\controller\api
	 */
	class Login extends Controller
	{
		/**
		 * 接口认证类型
		 * @var string
		 */
		private $type;

		/**
		 * 控制器初始化
		 */
		protected function initialize()
		{
			// 接收接口类型
			$this->type = $this->request->request('api');
			$this->type = $this->type ?: $this->request->header('api-name');
			$this->type = $this->type ?: $this->request->header('api-type');
			$this->type = $this->type ?: UserAdminService::API_TYPE_WAP;
			if (empty(UserAdminService::TYPES[$this->type])) {
				$this->error("接口支付[{$this->type}]未定义规则！");
			}
		}

		/**
		 * 用户登录接口
		 * @throws \think\admin\Exception
		 * @throws \think\db\exception\DataNotFoundException
		 * @throws \think\db\exception\DbException
		 * @throws \think\db\exception\ModelNotFoundException
		 */
		public function in()
		{
			$data = $this->_vali([
				'phone.mobile' => '手机号码格式错误！',
				'phone.require' => '手机号码不能为空！',
//            'password.require' => '登录密码不能为空！',
			]);
			$map = ['deleted' => 0, 'phone' => $data['phone']];
			$user = DataUser::mk()->where($map)->findOrEmpty();
			if ($user->isEmpty()) $this->error('该手机号还没有注册哦！');
			if (empty($user['status'])) $this->error('该用户账号状态异常！');
//        if (md5($data['password']) === $user['password']) {
			if ($data['phone'] == $user['phone']) {
				$this->success('手机登录成功！', UserAdminService::set($map, [], $this->type, true));
			} else {
				$this->error('账号登录失败，请稍候再试！');
			}
		}

		/**
		 * 用户统一注册入口
		 * @throws \think\admin\Exception
		 * @throws \think\db\exception\DbException
		 */
		public function register()
		{
			// 0 手机登录 1微信登录
			$login_type = input('login_type');
			if ($login_type == '0') {
				$data = $this->_vali([
					'nickname.default' => '',
					'username.default' => '',
//            'phone.mobile'            => '手机格式错误！',
					'phone.require' => '手机不能为空！',
					'headimg.default' => '！',
//            'verify.require'          => '验证码不能为空！',
				]);
			} else {
				$data = $this->_vali([
					'nickname.default' => '',
					'username.default' => '',
//            'phone.mobile'            => '手机格式错误！',
//                 'phone.require' => '手机不能为空！',
					'headimg.default' => '！',
//            'verify.require'          => '验证码不能为空！',
				]);
			}
//        if (!MessageService::instance()->checkVerifyCode($data['verify'], $data['phone'])) {
//            $this->error('手机短信验证失败！');
//        }
//        $map = ['phone' => $data['phone'], 'deleted' => 0];
//        if (DataUser::mk()->where($map)->count() > 0) {
//            $this->error('手机号已注册，请使用其它手机号！');
//        }


			//先去查询是否为公证员的手机号

			if ($login_type == '0') {
				$is_notary = SystemUser::mk()->where(['contact_phone' => input('phone'), 'is_deleted' => 0, 'status' => 1])->findOrEmpty();
				if (!empty($is_notary) && $is_notary['id'] > 0) {
					$is_notary['is_notary'] = true;

					$appid = sysconf('wechat.appid');
					$secret = sysconf('wechat.appsecret');
					$code = input('code');
					$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
					// $data_string = json_encode(['UserID'=>$phone,'Nick'=>'','FaceUrl'=>'']);
					$ch = curl_init();
					$timeout = 20;
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
					// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					$file_contents = curl_exec($ch);
					curl_close($ch);
					$arr = json_decode($file_contents, true);

					if (isset($arr['openid'])) {
						$openid1 = $arr['openid'];
						//给公证员 添加open_id;
						SystemUser::mk()->where(['contact_phone' => input('phone'), 'is_deleted' => 0, 'status' => 1])->update(['openid1'=>$openid1]);
					} else {
						$this->error('调用接口出错');
					}
					$this->success('公证员登录！', $is_notary);
				}

				if (!empty($this->request->header('token'))) {
					$map = ['token' => $this->request->header('token')];
					$user = DataUserToken::mk()->where($map)->findOrEmpty();

					// if ($user->isEmpty()) $this->error('该手机号还没有注册哦！');
					if ($user) {
						if (!empty($user)) {

							// if (empty($user['status'])) $this->error('该用户账号状态异常！');
							// if ($data['phone'] == $user['phone']) {
							//     $map = ['id' => $user['uuid']];
							//     $this->success('手机登录成功！', UserAdminService::set($map, [], $this->type, true));
							// } else {
							//     $this->error('账号登录失败，请稍候再试！');
							// }
						}
						// if ($user->isEmpty()) $this->error('该手机号还没有注册哦！');
						// if (empty($user['status'])) $this->error('该用户账号状态异常！');
						// if ($data['phone'] == $user['phone']) {
						//     $map = ['id' => $user['uuid']];
						//     $this->success('手机登录成功！', UserAdminService::set($map, [], $this->type, true));
						// } else {
						//     $this->error('账号登录失败，请稍候再试！');
						// }
					}
				}
			}


//        $data['password'] = md5($data['password']);
			$where = input('get.where');
			if ($where == 1) {
				return '';
			} else {

				if ($login_type == '0') {
					$map = ['phone' => $data['phone'], 'deleted' => 0];
				} else {
					$map = ['openid1' => null];
				}

				// $user = DataUser::mk()->where($map)->findOrEmpty();

				//该手机号还没有注册哦
				// if ($user->isEmpty()) {
				// 根据code 获取 openid
				$appid = sysconf('wechat.appid');
				$secret = sysconf('wechat.appsecret');
				$code = input('code');
				$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
				// $data_string = json_encode(['UserID'=>$phone,'Nick'=>'','FaceUrl'=>'']);
				$ch = curl_init();
				$timeout = 20;
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
				// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
				$file_contents = curl_exec($ch);
				curl_close($ch);
				$arr = json_decode($file_contents, true);
				if (isset($arr['openid'])) {
					$data['openid1'] = $arr['openid'];
					if ($login_type == '0') {

					} else {
						$map['openid1'] = $data['openid1'];
					}
				} else {
					$this->error('调用接口出错');
				}
				// }

				$user = UserAdminService::set($map, $data, $this->type, true);
				$user['arr'] = $arr;
				empty($user) ? $this->error('手机注册失败！') : $this->success('用户注册成功！', $user);
			}

		}


		/**
		 * 发送短信验证码
		 * @throws \think\db\exception\DataNotFoundException
		 * @throws \think\db\exception\DbException
		 * @throws \think\db\exception\ModelNotFoundException
		 */
		public function sendsms()
		{
			$data = $this->_vali([
				'phone.mobile' => '手机号格式错误！',
				'phone.require' => '手机号不能为空！',
				'secure.require' => '安全码不能为空！',
			]);
			if ($data['secure'] !== sysconf('zt.secure_code')) $this->error('接口安全码错误！');
			[$state, $message, $data] = MessageService::instance()->sendVerifyCode($data['phone']);
			$state ? $this->success($message, $data) : $this->error($message, $data);
		}

		public function sendcode()
		{
			$phone = input("phone");
			$data = $this->_vali([
				'phone.mobile' => '手机号格式错误！',
			]);

			$m = new Sendsms();
			$SecretId = sysconf('vx.secretId');
			$SecretKey = sysconf('vx.secretKey');
			$code = $m->Sms($phone, $SecretId, $SecretKey);

			// $code = '1234';
			$this->success('成功',$code);
			// $redis = new Redis();
			// $redis->connect('localhost', 6379);
			// $redis->set($code, json_encode($user), 2400000);
			// $res = $redis->get($code);
		}

		public function getnotaryorder()
		{
			//获取公证员的带视频认证订单
			if ($this->request->isPost()) {

				$where = [];
				//公证员id
				$is_notary = input('is_notary', 0);
				$order_status = input('order_status', 0); //订单状态(0进行中,1已完成)
				// 订单流程状态(0已取消,1信息确认中,2信息有误,3待认证,4待视频取证,5认证通过,6认证失败,7审批人审核,8已完成)
				if ($order_status == 1) {
					$where[] = ['status', '=', 5];
				} else if ($order_status == 0) {
					$where[] = ['status', '=', 4];
				}

				$where[] = ['system_user_id', '=', $is_notary];
				$where[] = ['deleted_status', '=', 0];


				$query = ShopOrder::mQuery()->in('status')->equal('order_no');
				$field = 'id,order_no,base_type,matter_id,client_name,client_phone,create_at,status,payment_status,reason_for_rejection,notarial_office_id,number_goods,amount_real,create_type,
            client_id_number,
            unified_numbering';
				// client_id_number,
				$append = ['status_text', 'type_text', 'matter_name', 'notarial_office_name'];
				$result = $query->field($field)->append($append)->where($where)->order('id desc')->page(true, false, false, 10);
				$this->success('获取订单数据成功！', $result);
			}
		}

		//获取公证员的签名
		public function getSign()
		{
			$record_id = input('record_id');
			//获取订单的审核员的id
			$record_data = ShopOrder::mk()
				->alias('a')
				->field('a.*,b.phone')
				->leftJoin('data_user b', 'a.uuid = b.id')
				->where(['a.id' => $record_id])->find();
			$user_id = strval($record_data['system_user_id']);
			$phone = $record_data['phone'];

			$appid = sysconf('vx.sdkappid');
			$appkey = sysconf('vx.sdkappkey');
			$api = new \Tencent\TLSSigAPIv2($appid, $appkey);


			//把人注册到通讯中
			$sig = $api->genUserSig('administrator');
			$random = random_int(0, 4294967295);
			//实时通讯 导入用户
			$url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" . $appid . "&identifier=administrator&usersig=" . $sig . "&random=" . $random . "&contenttype=json";
			$data_string = json_encode(['UserID' => $phone, 'Nick' => '', 'FaceUrl' => '']);
			$ch = curl_init();
			$timeout = 20;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			$file_contents = curl_exec($ch);
			curl_close($ch);
			// var_dump($data_string);
			// var_dump($file_contents);
			// return 1;
			$arr = json_decode($file_contents, true);
			if ($arr['ErrorCode'] == '0') {

			} else {
				$this->error('调用接口出错');
			}

			$sig = $api->genUserSig($user_id);
			$rt = [];
			$rt['sdkAppID'] = intval($appid);
			$rt['phone'] = $user_id;
			$rt['system_user_id'] = strval($phone);
			$rt['sign'] = $sig . "\n";
			$this->success('获取成功', $rt);
			// echo $sig . "\n";
		}

		//阿里云视频录制回调
		public function video_record()
		{
			$data = input();
			$string = json_encode($data);
			$data = json_decode($string, true);
			$EventType = $data['EventType'];
			if ($EventType == '311') {
				$EventInfo = $data['EventInfo'];
				$RoomId = $EventInfo['RoomId'];
				$VideoUrl = $EventInfo['Payload']['TencentVod']['VideoUrl'];
				$order = ShopOrder::mk()->where(['id' => $RoomId])->find();
				$video = json_decode($order['video_src'], true) ?? [];

				// fwrite($fp, $VideoUrl );
				array_push($video, $VideoUrl);

				ShopOrder::mk()->where(['id' => $RoomId])->update(['video_src' => json_encode($video)]);
			}
			return json_encode(['code' => 0]);
		}


		//百度云视频录制回调
		public function du_video_record()
		{
			$data = input();
			$string = json_encode($data);
			$data = json_decode($string, true);
			$EventInfo = $data['eventInfo'];
			$RoomId = $data['roomName'];
			$VideoUrl = $EventInfo['fileInfo']['fileUrl'];
			$order = ShopOrder::mk()->where(['id' => $RoomId])->find();
			$video = json_decode($order['video_src'], true) ?? [];
			// fwrite($fp, $VideoUrl );
			array_push($video, $VideoUrl);

			ShopOrder::mk()->where(['id' => $RoomId])->update(['video_src' => json_encode($video)]);
			return json_encode(['code' => 0]);
		}

		//公证员角度: 获取微信双人视频通话参数
		public function getParams(){

			$record_id = input('record_id');
			//获取订单的审核员的id
			$record_data = ShopOrder::mk()
				->alias('a')
				->field('a.*,b.phone')
				->leftJoin('data_user b', 'a.uuid = b.id')
				->where(['a.id' => $record_id])->find();
			$user_id = strval($record_data['system_user_id']);

			$uuid = $record_data['uuid'];


			$user = SystemUser::mk()->where(['id' => $user_id])->find();


	        $nickname = $user['nickname'];
	        $headImage = $user['headimg'];
	        $openid = $user['openid1'];
	        $caller = [
	            'nickname'=>$nickname,
		        'headImage'=>$headImage,
		        'openid'=>$openid,
	        ];
	        $order_user = DataUser::mk()->where(['id' => $uuid])->find();
	        if (!empty($order_user)){
	            $listener = [
					'nickname'=>$order_user['nickname'],
			        'headImage'=>$order_user['headimg'],
			        'openid'=>$order_user['openid1'],
		        ];
	            $data['caller'] = $caller;
	            $data['listener'] = $listener;
	            $this->success('成功', $data);
	        }else{
	            $this->error('订单的人不存在');
	        }
	    }
	}